package com.yumeng.framework.auth.security.authentication.sms;

import com.yumeng.common.helper.AssertHelper;
import com.yumeng.framework.auth.security.authentication.custom.CustomAbstractAuthenticationProcessingFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * 短信验证码登录认证过滤器
 *
 * @author wxd
 * @date 2025/4/8 15:20
 */
public class SmsLoginAuthenticationFilter extends CustomAbstractAuthenticationProcessingFilter {

    /** 参数名-用户名 */
    private String phoneParameter = "phone";
    /** 参数名-密码 */
    private String smsCodeParameter = "smsCode";


    private static final RequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, "/smsLogin");

    public SmsLoginAuthenticationFilter() {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
    }

    public SmsLoginAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager);
    }

    @Override
    protected AbstractAuthenticationToken obtainAuthenticationToken(HttpServletRequest request) {
        String phone = request.getParameter(this.phoneParameter);
        String smsCode = request.getParameter(this.smsCodeParameter);
        phone = (phone != null) ? phone.trim() : "";
        smsCode = (smsCode != null) ? smsCode.trim() : "";
        return SmsLoginAuthenticationToken.unauthenticated(phone, smsCode);
    }

    @Override
    protected AbstractAuthenticationToken obtainAuthenticationTokenForJson(HttpServletRequest request) {
        throw new AuthenticationServiceException("暂未实现json格式传参模式");
    }

    public void setPhoneParameter(String phoneParameter) {
        AssertHelper.assertNotBlank(phoneParameter, "Phone parameter must not be empty or null");
        this.phoneParameter = phoneParameter;
    }

    public void setSmsCodeParameter(String smsCodeParameter) {
        AssertHelper.assertNotBlank(smsCodeParameter, "SmsCode parameter must not be empty or null");
        this.smsCodeParameter = smsCodeParameter;
    }

}
